/*
 * JSONPullParser.fx
 *
 * Created on 29 Jul 09, 22:40:59
 */

package gtranslatefx;
import javafx.data.pull.Event;
import javafx.data.pull.PullParser;
import javafx.io.http.HttpRequest;
import java.net.URLEncoder;
/**
 * @author Muhammad Hakim A
 */

public class Translate {
    public var translatedText; //result
    var request:HttpRequest;
    var parser:PullParser;
    var url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0";
    //"&key=ABQIAAAAUFZNk8gVL8zah_oL1CYLyxRywcYF9YaJQsRRJIwnvjtCuKJLXRRZR1ZaQpePq90vbt0N7F0ux8pYqw";

    public function translate (text:String,From:String, to:String):Void {
        request = HttpRequest{
            def location = "{url}&q={URLEncoder.encode(text,"UTF-8")}&langpair={From}%7C{to}";
            location: location;

            onInput: function(input: java.io.InputStream) {
                try {
                    parser = PullParser {
                        documentType: PullParser.JSON;
                        input: input;
                        onEvent: parseEventCallback;
                    };
                    parser.parse();
                } finally {
                    input.close();
                }
            }

            onDone: function(){
                Main.jtextTo.setText(translatedText);
            }

            onException: function(e:java.lang.Exception){
                println("exception {e.getMessage()}");
            }
        }
        request.start();
    }

    /*sample json result
    {"responseData": {
    "translatedText":"Ciao mondo"
     },
     "responseDetails": null, "responseStatus": 200}
    */
    public function parseEventCallback(event:Event) {
        if (event.type == PullParser.END_VALUE) {
            if (event.name == "translatedText") {
                translatedText = HTMLEntities.unhtmlentities(event.text);
            }
        }
    }
}
